<template>
  <div class="page">
    <div class="bento-grid">
      <app-bento-item title="数据模块B" :style="`grid-column: span 3;`"> </app-bento-item>

      <Test />

      <component v-for="(item, key) in components" :is="item"></component>
    </div>
  </div>
</template>
<script setup>
import { defineAsyncComponent, ref, onMounted } from 'vue'
import * as Vue from 'vue'

import { loadModule } from 'vue3-sfc-loader'

import axios from 'axios'

import Test from './components/Test.vue'

const components = reactive({})

onMounted(() => {
  axios.get('/components.json').then(res => {
    res.data.forEach(async (filename, index) => {
      const name = filename.split('.')[0]

      components[name] = loadRemoteComponent(`/remote-component/${filename}`)
    })
  })

  // components.A = loadRemoteComponent('/remote-component/a6e74a11-9edd-4ac7-81ec-e8755577e043.vue')
})

function loadRemoteComponent(url) {
  return defineAsyncComponent(async () => {
    const res = await loadModule(url, {
      moduleCache: {
        vue: Vue,
      },
      async getFile(url) {
        const res = await fetch(url)
        const code = await res.text()
        return code
      },
      addStyle(textContent) {
        const style = Object.assign(document.createElement('style'), {
          textContent,
        })
        const ref = document.head.getElementsByTagName('style')[0] || null
        document.head.insertBefore(style, ref)
      },
    })
    return res
  })
}
</script>
<style lang="scss" scoped>
.page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.bento-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  // grid-auto-rows: minmax(120px, 360px);
  // grid-auto-rows: 300px;
  // grid-auto-rows: minmax(120px, auto);
  gap: 1rem;
  max-width: 1200px;
  margin: 0 auto;
}
</style>
